import { getAuthCode } from "dingtalk-jsapi";
import { login as loginFromApi } from "@/api/login";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia"

export async function login() {
	await uni.showLoading({ title: "登录中" })
	await getAuthCode({
		corpId: import.meta.env.VITE_CORP_ID,
		async success({ authCode, code } : { authCode : string, code : string }) {
			let finalCode : string | undefined = undefined
			if (authCode !== undefined) {
				finalCode = authCode
			} else if (code !== undefined) {
				finalCode = code
			}
			if (finalCode !== undefined) {
				try {
					const { data } = await loginFromApi(finalCode)
					const { isHr, isManager, token } = storeToRefs(useUserStore())
					if (data !== undefined) {
						token.value = data.data?.token
						isHr.value = data.data?.is_hr === 1
						isManager.value = data.data?.is_manager === 1
					}
				} catch (error) {
					uni.hideLoading()
					uni.showToast({
						title: "登录失败",
						duration: 2000,
						icon: "error"
					})
					console.error("登录失败下↓↓")
					console.error(error)
				}


			}
		},
		fail({ error } : { error : string, errorMessage : string }) {
			if (error == "1002") {
				uni.showToast({
					title: "登录失败，该不在不在企业中"
				})
			}
			uni.hideLoading()
		},
	})
}

export function isLogin() {
	const { token } = storeToRefs(useUserStore())
	return token.value !== undefined
}